package utils;

import java.io.FileWriter;
import java.io.IOException;

import inf.minife.fe.DOF;
import inf.minife.fe.Element;
import inf.minife.fe.Model;
import inf.minife.fe.Node;
import inf.minife.fe.Truss2D;


public class MWUtils {
	/* Information tag to use between Master-Worker communication */
	public final int WORK_TAG = 1;
	public final int DATA_TAG = 2;
	public final int STOP_TAG = 3;
	
	public double random(double high_val, double low_val){
		
		double random_val;
		
		if(low_val >= high_val){
			throw new java.lang.IllegalArgumentException("Low value is larger or equal high value: " 
					+ low_val + " >= " + high_val);
		}
		
		random_val = Math.random()*(high_val - low_val) + low_val;
		
		return random_val;
	}
	
	public double[] computeStressConstrains(Model newModel, double sigmaMax){
		Element[] elements = newModel.getElements();
		int n = elements.length;
		
		double sigma;
		double[] f = new double[n];
		for (int i = 0; i < n; i++) {
			sigma = elements[i].getResult(Truss2D.RS_STRESS);
			f[i] = Math.abs(sigma) / sigmaMax - 1.0;
		}
		return f;
	}
	
	public double[] computeDispXConstrains(Model newModel, double uMax){
		Node[] nodes = newModel.getNodes();
		int m = nodes.length;
		double u;
		double[] g = new double[m];
		for (int i = 0; i < m; i++) {
			u = nodes[i].getResult(DOF.T_X);			
			g[i] = Math.abs(u) / uMax - 1.0;
		}
		return g;
	}
	
	public double[] computeDispYConstrains(Model newModel, double uMax){
		Node[] nodes = newModel.getNodes();
		int m = nodes.length;
		double u;
		double[] g = new double[m];
		for (int i = 0; i < m; i++) {
			u = nodes[i].getResult(DOF.T_Y);			
			g[i] = Math.abs(u) / uMax - 1.0;
		}
		return g;
	}
	
	public void printResult(String filename, String textwrite) {
		
		FileWriter out;
        if (filename == null) {
            System.out.println("Must specify file on the command line");
            return;
        }
        try {
            out = new FileWriter(filename, true);
            out.write(textwrite);
            out.close();
        } catch(IOException e) {
            System.out.println("Error appending to file " + filename);
            return;
        }
		
	}
}
